package clientCommunicationHandler;

import client.TelnetClient;


public class ClientServerMsgHandler {
	
	public static boolean isReady = false;
	public static boolean buildMenu = true;
	
	public ClientServerMsgHandler(){

	}

	public void parseServerMsg(String serverMsg){
		String tMsg = serverMsg;
		//		System.out.println("parsing msg :"+serverMsg);
		String serverCommand = tMsg.split("\n")[0];
		if(serverCommand.equalsIgnoreCase("subForumList")){
			TelnetClient.menu = buildNewViewMenu(tMsg,"viewSubForum");	
		}
		else{
			if(serverCommand.equalsIgnoreCase("threadsList")){
				this.handleThreadListMsg(tMsg);
				TelnetClient.SubForumId = TelnetClient.tempSubForumID;
			}
			else{
				if(serverCommand.equalsIgnoreCase("postList")){
					this.handlePostListMsg(tMsg);
				}
				else{
					if(serverCommand.equalsIgnoreCase("logout")){
						this.handleLogoutMsg(tMsg);
					}
					else{
						if(serverCommand.equalsIgnoreCase("login")||serverCommand.equalsIgnoreCase("register")){
							this.loginToSystem(serverCommand,tMsg);
						}
						else{
							if(serverCommand.equalsIgnoreCase("addPostMessage")){
								System.out.println("addedNewPostMesg");
								ClientServerMsgHandler.buildMenu = false;
							}
							else{
								System.out.println(tMsg);
							}
						}
					}
				}
			}
		}
		
		this.buildUserUpdatedMenu(serverCommand);
	}

	private void buildUserUpdatedMenu(String serverCommand) {
		if(!(serverCommand.equals("addThread"))){
			TelnetClient.menu = new StringBuilder("[user: "+TelnetClient.userName+"] "+"please make your choice:\n\t1. "+
					(TelnetClient.userName.equalsIgnoreCase("guest")? "Login\n\t2. Register\n":"Logout\n")+
					getRestOfTheMenu(TelnetClient.userName.equalsIgnoreCase("guest")? 3:2));
			synchronized (ClientServerMsgHandler.class) {
				if(ClientServerMsgHandler.buildMenu == true){//to ensure that new login user will see the correct menu
					isReady = true;
					ClientServerMsgHandler.class.notifyAll();
				}
				else {
					ClientServerMsgHandler.buildMenu = true;
				}
			}
		}

	}

	private void handleLogoutMsg(String tMsg) {
		TelnetClient.userName = "guest";
		TelnetClient.menu = TelnetClient.welcom_page;	
	}

	private void handlePostListMsg(String tMsg) {
		String [] serverMsgs = tMsg.split("\n");
		TelnetClient.menu = buildNewViewPosts(tMsg,"viewThread");
		TelnetClient.threadId = TelnetClient.tempThreadID;
	}
	private StringBuilder buildNewViewPosts(String tMsg, String string) {	
		String [] subForumList = tMsg.split("\n");
		StringBuilder tSb = new StringBuilder();
		int counter = 1 ; 
		String [] postsIds =  new String[(subForumList.length -1)/2];
		for(int i = 1 ;i < subForumList.length ;i = i+ 2){
			postsIds[counter -1] = getPostId(subForumList[i]);
			tSb.append("\n\t"+counter+". postId "+subForumList[i]+" content: "+subForumList[i+1]);
			counter++;
		}
		//allow to add a new msg if the user is not a guest and his current possition is not sub-Forum 
		if(!(TelnetClient.userName.equals("guest"))){
			for(int j = 0 ; j <postsIds.length ; j++){
				tSb.append("\n\t"+counter+". "+"addPost " + postsIds[j]);
				counter++;
			}
		}
		tSb.append("\n\t"+counter +". "+"back");
		tSb.append("\n\t"+counter +". "+"exit\n");
		return tSb;
	}


	private String getPostId(String string) {
		String [] tempArray = string.split(":");
		return tempArray[0];
	}

	private void handleThreadListMsg(String tMsg) {
		TelnetClient.menu = buildNewViewMenu(tMsg,"viewThreads");
		//				TelnetClient.SubForumId = Integer.parseInt(tMsg.split("\n")[1]);
		TelnetClient.threadId = -1;

	}

	/**
	 * 
	 * @param tMsg the server msg
	 * @param view king of view we want to send
	 * @return
	 */
	public StringBuilder buildNewViewMenu(String tMsg,String view) {
		String [] subForumList = tMsg.split("\n");
		StringBuilder tSb = new StringBuilder();
		int counter = 1 ; 
		for(int i=1;i<subForumList.length;i++){
			tSb.append("\n\t"+i+". "+view+" "+subForumList[i]);
			counter++;
		}
		//allow to add a new msg if the user is not a guest and his current possition is not sub-Forum 
		if((!(TelnetClient.userName.equals("guest"))) && (!view.equals("viewSubForum"))){
			tSb.append("\n\t"+counter+". "+"add");
			counter++;
		}
		if(!view.equalsIgnoreCase("ViewSubForum"))
			tSb.append("\n\t"+counter +". "+"back");
		tSb.append("\n\t"+counter +". "+"exit\n");
		return tSb;
	}
/***
 * 
 * @param i 2 if user loged in 3 if user in a guest mode
 * @return rest of the menu without login/logout/register
 */
	public String getRestOfTheMenu(int i) {
		String[] tSplitMenu = TelnetClient.menu.toString().split("\n\t");
		StringBuilder tempResult = new StringBuilder();
		int tCounter = i;
		for(int j=1;j<tSplitMenu.length;j++){
			if(!(tSplitMenu[j].split(" ")[1].equalsIgnoreCase("login")||tSplitMenu[j].split(" ")[1].equalsIgnoreCase("register")||tSplitMenu[j].split(" ")[1].equalsIgnoreCase("logout"))){
				if( j == tSplitMenu.length-1 )
					tempResult.append("\t"+tCounter+". "+tSplitMenu[j].substring(3));
				else
					tempResult.append("\t"+tCounter+". "+tSplitMenu[j].substring(3)+"\n");
				tCounter++;
			}
		}
		return tempResult.toString();
	}

	private String loginToSystem(String serverCommand,String serverMsg){
		String success = serverMsg.split("\n")[1];
		String tMsg = serverCommand;
		if(success.equals("success")){
			TelnetClient.userName = TelnetClient.tempUserName;
			TelnetClient.menu = new StringBuilder("[user: "+TelnetClient.userName+"] "+TelnetClient.menu);
		}
		else{
			tMsg = new String("your "+(serverCommand.equalsIgnoreCase("login")?"login":"registration")+" failed: "+serverMsg.split("\n")[2]);
			TelnetClient.menu = new StringBuilder(tMsg + TelnetClient.menu);
//			System.out.println(TelnetClient.menu);
//			TelnetClient.menu = TelnetClient.welcom_page;
			TelnetClient.transmitToServer = false;
		}
		return tMsg;
	}

}
